
#include <string.h>

#include "Des.h"

#include "ISO14443Command.h"
#include "CardCommandDefine.h"
#include "CardCommand.h"
//PICC
#include "CardPort.h"
#include "CardPrivate.h"
#include "ISO14443p3a.h"
#include "ISO14443p3b.h"
#include "CardMem.h"
//ICC
#include "Slot.h"
#include "Driver.h"
#include "Bsp.h"

#include "Reader.h"
#include "ReaderA.h"
#include "ReaderSFZ.h"
#include "ReaderISO15693.h"
#include "ReaderQr.h"
#include "Env.h"

#include "Debug.h"



static uint8_t readerState;
static uint8_t readerCurType;
static uint8_t readerCount;

void Reader_Init(void){
	readerState = 0;	
	Port_Picc_SetRf(0);
	Reader_QR_Init();
}

static int Reader_Detect(uint8_t type, int timeout){
	if(type == Card_T_CpuA){
		return Reader_DetectTypeA(timeout);
	}
	if(type == Card_T_CpuB){
		return Reader_DetectTypeB(timeout);
	}
	if(type == TAG_TypeV){
		return Reader_Read15963(NULL) == 0;
	}
	return 0;
}


static int Reader_Transfer(int ret){
	if(ret == 0){
		return 1;
	}
	if(ret == -100){
		return 2;
	}
	if(ret == -101){
		return 3;
	}
	return 0;
}

static void Reader_CSN_Select(CSN_T* csn){
	uint8_t buf[16];
	uint8_t pos;
	uint8_t len;
	uint8_t i;
	
	if(csn->info){
		//逻辑卡号，在读卡时已经截取，无需再此截取。
		return;
	}
	
	if(csn->nlen != 4){
		pos = envData.Snr8_StartPos;
		len = envData.Snr8_Len;
	}
	else{
		pos = envData.Snr4_StartPos;
		len = envData.Snr4_Len;
	}
	
	if(len > 8){
		len = 8;
	}
	
	//根据长度和起始位置截取卡号，不足补0
	memcpy(buf, csn->num, csn->nlen);
	memset(csn->num, 0, sizeof(csn->num));
	for(i = 0; i < len; i++){
		if(pos < csn->nlen){
			csn->num[i] = buf[pos];
			pos++;
		}
		else{
			break;
		}
	}
	
	csn->nlen = len;
}

int Reader_CSN_Service(CSN_T* csn){
	int ret = -1;
	
	switch(readerState){
	case 0:{
		uint8_t select = envData.rdSupport[0];
		if(!(select & (ENV_Func_CPU | ENV_Func_MF | ENV_Func_SFZ |ENV_Func_15693))){
			break;
		}
		
		Port_Picc_SetRf(1);
		if(csn->nlen || csn->ilen){
			memset(csn, 0, sizeof(*csn));
		}
		if(select & (ENV_Func_CPU | ENV_Func_MF)){
			ret = Reader_ReadTypeA(csn);
			if(ret != -200){
				if(Reader_Transfer(ret)){
					//读卡成功或者密钥错误，等待卡离开
					readerCurType = Card_T_CpuA;
					readerState = 1;
					readerCount = 0;
				}
				break;
			}
		}
		
		if(select & ENV_Func_SFZ){
			ret = Reader_ReadTypeB(csn);
			if(!ret){
				readerCurType = Card_T_CpuB;
				readerState = 1;
				readerCount = 0;
				break;
			}
		}
		
		if(select & ENV_Func_15693){
			ret = Reader_Read15963(csn);
			if(!ret){
				readerCurType = TAG_TypeV;
				readerState = 1;
				readerCount = 0;
				break;
			}
		}
	}
	break;
	
	case 1:{
		ret = 1;
		Port_Picc_SetRf(1);
		BSP_Sleep_Ms(10);
		int status = Reader_Detect(readerCurType, 100);
		if(!status){
			if(++readerCount > 1){
				//多次连续寻卡失败，卡已经离开
				readerState = 0;
				readerCount = 0;
				ret = 2;
			}
		}
	}
	break;
	default :{
		readerState = 0;
	}
	break;
	}
	Port_Picc_SetRf(0);
	if(!ret){
		//根据配置截取卡号
		Reader_CSN_Select(csn);
	}
	return ret;
}




